<template>
  <div class="edu-page-warp">
    <el-card shadow="never">
      <section>
        <div class="questionnaire-maintain-head">{{`${ifProcess ? '过程' : '课程'}评价题目维护`}}</div>
        <div class="questionnaire-maintain-title-container">
          <div class="title-text">{{`${ifProcess ? '过程' : '课程'}评价模板名称：`}}</div>
          <div class="title-content">
            <el-input v-model="name" disabled></el-input>
          </div>
        </div>
      </section>
      <edu-form :model="maintainForm" ref="maintainForm" label-width="120px">
        <section class="question-item-container"
          v-for="(item, index) in maintainForm.titleContentDtoList"
          :key="index"
          :class="{active : activeBtn == index+1,danger : dangerBtn == index+1}"
          :style="{'border-color': fatherSelcetSortList.indexOf(index+1) >=0 ? 'blue' : '#ccc'}">
          <section
            :style="{'border': validWeightArr.indexOf(index+1) >=0
                            || validTitleArr.indexOf(index+1) >=0
                            || sameOptResArr_.indexOf(index+1) >=0
                            ? '1px solid red' : ''}">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item :label="$t('排序')" prop="sort">
                  <el-input-number style="width: 100%;" v-model="item.sort" :disabled="true"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="$t('题目类型')" prop="titleType" class="is-required">
                  <el-select
                    :disabled="ifWithDrawMaintan"
                    @change="changeQuestionType(item, $event)"
                    v-model="item.titleType" style="width: 100%;">
                    <el-option
                      v-for="item in typeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :label="$t('权重')" prop="weight" :class="{'is-required':item.titleType == 1}">
                  <el-input v-model="item.weight" @keypress.native="commonMethod"
                    oninput="if(Number(value) > 100)value = 100"
                    :disabled="item.titleType !== 1 || ifProcess || ifWithDrawMaintan">
                    <template slot="append">%</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="text-align: right;">
                <el-button v-if="item.sort > 1" :disabled="ifWithDrawMaintan" @click="goUp(item, $event)">上移</el-button>
                <el-button
                  v-if="item.sort < maintainForm.titleContentDtoList.length"
                  :disabled="ifWithDrawMaintan"
                  @click="goDown(item, $event)">下移</el-button>
                <el-button
                  @click="deleteQuestionItem(item, $event)"
                  :disabled="ifWithDrawMaintan">删除</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('题目内容')" prop="title" class="is-required">
                  <el-input v-model="item.title" maxlength="64">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 单选/多选 -->
            <el-row v-if="item.titleType === 1 || item.titleType === 2">
              <el-col :span="12"
                v-for="(item1, index1) in item.options"
                :key="index1">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item :label="item1.option" class="is-required">
                      <el-input v-model="item1.des" maxlength="32"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="分值">
                      <el-input
                        v-model="item1.score"
                        @keypress.native="commonMethod"
                        oninput="if(Number(value) > 100)value = 100"
                        :disabled="item.titleType === 2 || ifProcess || ifWithDrawMaintan">
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="text" :disabled="ifWithDrawMaintan" @click="deleteOptionClick(item, item1)">删除</el-button>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="10">
                <el-form-item>
                  <el-button
                    style="width: 100%;"
                    type="primary"
                    plain icon="el-icon-plus"
                    :disabled="ifWithDrawMaintan"
                    @click="addOptionClick(item, $event)">
                    新增选项
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 问答 -->
            <el-row v-if="item.titleType === 3">
              <el-col :span="24">
                <el-form-item :label="$t('答案')" prop="answer">
                  <el-input readonly type="textarea" :rows="4" v-model="item.answer">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </section>

        </section>
      </edu-form>
      <section>
        <el-button
          style="width: 100%;" type="primary"
          plain icon="el-icon-plus"
          :disabled="ifWithDrawMaintan"
          @click="addQuestionItem()">
          新增题目
        </el-button>
      </section>
      <section>
        <div class="footer-container">
          <el-button @click="cancel">取消</el-button>
          <el-button @click="save" type="primary">保存</el-button>
        </div>
      </section>
    </el-card>
  </div>
</template>
<script>
import templateApi from 'common/src/api/teachingEvaluation/template'
export default {
  name: 'QuestionnaireMaintain',
  props: {
    questionList: {
      type: Array,
      default: () => {
        return []
      }
    },
    fatherSelcetSortList: {
      type: Array,
      default: () => {
        return []
      }
    },
    ifWithDrawMaintan: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      typeList: [
        {
          label: '单选题',
          value: 1
        },
        {
          label: '多选题',
          value: 2
        },
        {
          label: '问答题',
          value: 3
        }
      ],
      name: '',
      maintainForm: {
        titleContentDtoList: []
      },
      activeBtn: 0,
      dangerBtn: 0,
      validWeightArr: [],
      validTitleArr: [],
      sameOptResArr_: [],
      ifProcess: false
    }
  },
  created() {
    this.name = this.$route.query.row.name
    // 获取选择的题号，由于可能先选题号较大的题目，所以需要先排序，便于跳转到最小的题号处
    this.maintainForm.titleContentDtoList = this.questionList
    if (this.fatherSelcetSortList.length > 0) {
      this.fatherSelcetSortList.sort((a, b) => {
        if (a < b) {
          return -1;
        } else if (a > b) {
          return 1;
        } else {
          return 0
        }
      })
      this.activeBtn = this.fatherSelcetSortList[0]
    }
  },
  mounted() {
    if (this.$route.query.ifProcess == true) {
      this.ifProcess = true
    } else {
      this.ifProcess = false
    }
    this.goAnchor()
  },
  methods: {
    //锚点跳转(跳转到选择的最小的题号)
    goAnchor() {
      if (this.fatherSelcetSortList.length > 0) {
        this.$el.querySelector('.active').scrollIntoView()
      } else {
        return
      }
    },
    // 新增选项
    addOptionClick(item, e) {
      // 获取当前题目的选项，从后面添加选项，65为大写字母A
      const length = this.maintainForm.titleContentDtoList[item.sort-1].options.length;
      this.maintainForm.titleContentDtoList[item.sort-1].options.push(
        {
          option: String.fromCharCode(65 + length),
          des: '',
          score: ''
        }
      )
    },
    // 更改题目类型
    changeQuestionType(item, e) {
      const currentIndex = item.sort
      // 改变题目类型的时候权重置为null
      this.maintainForm.titleContentDtoList[currentIndex-1]['weight'] = null
      // 如果题目类型是问答题 则清空所有的选项，反之，默认添加4个选项，内容分值自填
      if (e === 3) {
        this.maintainForm.titleContentDtoList[currentIndex-1]['options'] = []
      } else {
        // this.maintainForm.titleContentDtoList[currentIndex-1]['options'] = [
        //   {
        //     option: 'A',
        //     des: '',
        //     score: null
        //   },
        //   {
        //     option: 'B',
        //     des: '',
        //     score: null
        //   },
        //   {
        //     option: 'C',
        //     des: '',
        //     score: null
        //   },
        //   {
        //     option: 'D',
        //     des: '',
        //     score: null
        //   }
        // ]
        this.maintainForm.titleContentDtoList[currentIndex-1]['options'].forEach(item => {
          item['score'] = null
        })
      }
    },
    // 删除选项
    deleteOptionClick(item, item1) {
      let currentOptIndex = 0
      // 先获取当前需要删除的选项index
      this.maintainForm.titleContentDtoList[item.sort-1].options.forEach((questionItem, index) => {
        if (questionItem.option === item1.option) {
          currentOptIndex = index
        }
      })
      // 如果当前只有一个选项的话 给出提示 最少为一个选项
      const length = this.maintainForm.titleContentDtoList[item.sort-1].options.length;
      if (length < 2) {
        this.$message.error('至少保留一个选项')
        return
      }
      // 删除当前选项
      this.maintainForm.titleContentDtoList[item.sort-1].options.splice(currentOptIndex, 1)
      // 删除后需要重置所有的选项
      this.resetOptionIndex(this.maintainForm.titleContentDtoList[item.sort-1].options)
    },
    // 重置选项顺序
    resetOptionIndex(data) {
      data.forEach((optionItem, index) => {
        optionItem['option'] = String.fromCharCode(65 + index)
      })
    },
    // 上移
    goUp(item, e) {
      let currentIndex = item.sort-1
      let itemNeedMove = this.maintainForm.titleContentDtoList.splice(currentIndex, 1)[0]
      this.maintainForm.titleContentDtoList.splice(currentIndex-1, 0, itemNeedMove)
      this.resetQuestionIndex()
    },
    // 下移
    goDown(item, e) {
      let currentIndex = item.sort-1
      let itemNeedMove = this.maintainForm.titleContentDtoList.splice(currentIndex, 1)[0]
      this.maintainForm.titleContentDtoList.splice(currentIndex+1, 0, itemNeedMove)
      this.resetQuestionIndex()
    },
    // 新增题目
    addQuestionItem() {
      const length = this.maintainForm.titleContentDtoList.length
      this.maintainForm.titleContentDtoList.push({
        sort: length+1,
        titleType: 1,
        weight: null,
        content: '',
        options: [
          {
            option: 'A',
            des: '',
            score: null
          },
          {
            option: 'B',
            des: '',
            score: null
          },
          {
            option: 'C',
            des: '',
            score: null
          },
          {
            option: 'D',
            des: '',
            score: null
          }
        ]
      })
    },
    // 删除题目
    deleteQuestionItem(item, e) {
      if (this.fatherSelcetSortList.indexOf(item.sort) >= 0) {
        this.$emit('removeCurrentSort', item)
      }
      let currentIndex = item.sort - 1
      this.maintainForm.titleContentDtoList.splice(currentIndex, 1)
      this.resetQuestionIndex()
    },
    // 重置问题顺序index
    resetQuestionIndex() {
      this.maintainForm.titleContentDtoList.forEach((item, index) => {
        item['sort'] = index + 1
      })
    },
    // 取消
    cancel() {
      this.$emit('goToPrev')
    },
    // 跳转到有错误的题目
    goToDanger() {
      this.$nextTick(() => {
        this.$el.querySelector('.danger').scrollIntoView()
      })
    },
    // 通用keypress方法
    commonMethod(event) {
      const regExp = /^[0-9]*$/
      if (String.fromCharCode(event.keyCode) === ' ') {
        event.returnValue = false
      }
      if (!regExp.test(Number(String.fromCharCode(event.keyCode)))) {
        event.returnValue = false
      } else {
        if (
          event.target.value.length === 1 && Number(event.target.value) === 0
          // Number(String.fromCharCode(event.keyCode)) === 0
        ) {
          event.returnValue = false
        } else {
          event.returnValue = true
        }
      }
    },
    // 保存
    save() {
      this.maintainForm.mainId = this.$route.query.row.id
      let weightSum = 0
      if (this.maintainForm.titleContentDtoList.length < 1) {
        this.$message.error('至少保留一个题目')
        return
      }
      this.maintainForm.titleContentDtoList.forEach((item, index) => {
        weightSum += Number(item.weight)
      })
      // 判断权重是否为100 不等于则给出提示 仍允许保存
      if (weightSum !== 100) {
        this.maintainForm.weightStatus = 0
      } else {
        this.maintainForm.weightStatus = 1
      }
      // 手动添加消息提示校验 筛选出来没有填写权重的单选题
      if (!this.ifProcess) {
        this.validWeightArr = []
        this.validWeightArr = this.maintainForm.titleContentDtoList.filter(item => {
          return item.titleType === 1 && (item.weight === '' || item.weight === null)
        })
        if (this.validWeightArr.length > 0) {
          this.validWeightArr = this.validWeightArr.map(item => {
            return item.sort
          })
          this.dangerBtn = this.validWeightArr[0]
          let validWeightStr = this.validWeightArr.toString()
          this.$alert(`第${validWeightStr}题权重不能为空`, '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.goToDanger()
            }
          });
          return
        }
      }
      // 手动添加消息提示校验 筛选出来没有填写题目内容的单选题
      this.validTitleArr = this.maintainForm.titleContentDtoList.filter(item => {
        return !item.title
      })
      if (this.validTitleArr.length > 0) {
        this.validTitleArr = this.validTitleArr.map(item => {
          return item.sort
        })
        this.dangerBtn = this.validTitleArr[0]
        let validWeightStr = this.validTitleArr.toString()
        this.$alert(`第${validWeightStr}题题目内容不能为空`, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.goToDanger()
          }
        });
        return
      }
      // 手动添加校验，判断题目名称是否相同，相同不能提交
      let validSameQuestionArr = this.maintainForm.titleContentDtoList.map(item => {
        return item.title.trim()
      })
      validSameQuestionArr = Array.from(new Set(validSameQuestionArr))
      if (validSameQuestionArr.length !== this.maintainForm.titleContentDtoList.length) {
        this.$alert(`存在相同的题目名称，请核对并修改！`, '提示', {
          confirmButtonText: '确定',
          callback: action => {}
        });
        return
      }
      // 手动添加校验，判断是否有相同选项的单选或者多选题
      let validSameOptArr = []
      validSameOptArr = this.maintainForm.titleContentDtoList.filter(item => {
        return item.titleType !== 3
      })
      let sameOptResArr = []
      validSameOptArr.forEach(item => {
        let arr_ = item.options.map(item1 => {
          return item1.des
        })
        arr_ = Array.from(new Set(arr_))
        if (item.options.length !== arr_.length) {
          sameOptResArr.push(item)
        }
      })
      if (sameOptResArr.length > 0) {
        this.sameOptResArr_ = sameOptResArr.map(item2 => {
          return item2.sort
        })
        this.dangerBtn = this.sameOptResArr_[0]
        let sameOptResString = this.sameOptResArr_.toString()
        this.$alert(`第${sameOptResString}题题目存在重复选项或选项为空，请核对并修改！`, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.goToDanger()
          }
        });
        return
      }
      // 手动添加校验，判断选项不能为空
      let ifNullOpt = false
      this.maintainForm.titleContentDtoList.some((item, index) => {
        if (item.options.length > 0) {
          item.options.some((item1, index1) => {
            if (!item1.des) {
              this.$message.error(`第${item.sort}题的${item1.option}选项为空，请填写`)
              ifNullOpt = true
              return true
            }
          })
        }
      })
      if (ifNullOpt) {
        return
      }
      let ifNullScore = false
      this.maintainForm.titleContentDtoList.some((item, index) => {
        if (!this.ifProcess && item.titleType == 1 && item.options.length > 0) {
          item.options.some(item1 => {
            if (!item1.score) {
              this.$message.error(`第${item.sort}题的${item1.option}选项分值为空，请填写`)
              ifNullScore = true
              return true
            }
          })
        }
      })
      if (ifNullScore) {
        return
      }
      // ==============================================
      if (!this.ifProcess) {
        if (weightSum !== 100) {
          this.$confirm(this.$t('单选题权重之和不等于100，确定提交？'), this.$t("message.prompt"), {
            confirmButtonText: this.$t("message.confirm"),
            cancelButtonText: this.$t("message.cancel"),
            type: "warning"
          }).then(() => {
            let param = JSON.parse(JSON.stringify(this.maintainForm))
            param.titleContentDtoList = param.titleContentDtoList.map(item => {
              return {
                sort: item.sort,
                titleType: item.titleType,
                weight: item.weight,
                title: item.title,
                options: item.options
              }
            })
            param.titleContentDtoList.forEach(item => {
              item['options'] = JSON.stringify(item['options'])
            })
            if (this.ifWithDrawMaintan) {
              let updateParam = param.titleContentDtoList.map(item => {
                return {
                  id: item.id,
                  title: item.title,
                  options: item.options
                }
              })
              templateApi.updateTitle(updateParam).then(res => {
                if (res.code === 200) {
                  this.$message.success('题目更新成功')
                  this.$emit('goToPrev')
                }
              })
            } else {
              templateApi.maintainTitle(param).then(res => {
                if (res.code === 200) {
                  this.$message.success('题目更新成功')
                  this.$emit('goToPrev')
                }
              })
            }
          });
        } else {
          let param = JSON.parse(JSON.stringify(this.maintainForm))
          param.titleContentDtoList = param.titleContentDtoList.map(item => {
            return {
              sort: item.sort,
              titleType: item.titleType,
              weight: item.weight,
              title: item.title,
              options: item.options,
              id: item.id
            }
          })
          param.titleContentDtoList.forEach(item => {
            item['options'] = JSON.stringify(item['options'])
          })
          if (this.ifWithDrawMaintan) {
            let updateParam = param.titleContentDtoList.map(item => {
              return {
                id: item.id,
                title: item.title,
                options: item.options
              }
            })
            templateApi.updateTitle(updateParam).then(res => {
              if (res.code === 200) {
                this.$message.success('题目更新成功')
                this.$emit('goToPrev')
              }
            })
          } else {
            templateApi.maintainTitle(param).then(res => {
              if (res.code === 200) {
                this.$message.success('题目更新成功')
                this.$emit('goToPrev')
              }
            })
          }
        }
      } else {
        let param = JSON.parse(JSON.stringify(this.maintainForm))
        param.titleContentDtoList = param.titleContentDtoList.map(item => {
          return {
            sort: item.sort,
            titleType: item.titleType,
            weight: item.weight,
            title: item.title,
            options: item.options,
            id: item.id
          }
        })
        param.titleContentDtoList.forEach(item => {
          item['options'] = JSON.stringify(item['options'])
        })
        if (this.ifWithDrawMaintan) {
          let updateParam = param.titleContentDtoList.map(item => {
            return {
              id: item.id,
              title: item.title,
              options: item.options
            }
          })
          templateApi.updateTitle(updateParam).then(res => {
            if (res.code === 200) {
              this.$message.success('题目更新成功')
              this.$emit('goToPrev')
            }
          })
        } else {
          templateApi.maintainTitle(param).then(res => {
            if (res.code === 200) {
              this.$message.success('题目更新成功')
              this.$emit('goToPrev')
            }
          })
        }
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.questionnaire-maintain-head {
  font-size: 18px;
  margin-bottom: 20px;
}
.questionnaire-maintain-title-container {
  display: flex;
  align-items: center;
  .title-text {
    width: 10%;
    text-align: right;
  }
  .title-content {
    width: 90%;
  }
}
.question-item-container {
  padding: 10px;
  margin: 10px 0;
  border: 1px solid #ccc;
  .danger {
    border-color: #f00;
  }
}
.footer-container {
  margin-top: 40px;
  padding: 20px 0;
  border-top: 1px solid #ccc;
  text-align: right;
}
</style>
